//
//  AsyncImageViewController.m
//  jungoo
//
//  Created by Vu Tu Cuong on 10/1/12.
//
//

#import "AsyncImageViewController.h"

@interface AsyncImageViewController ()

@end

@implementation AsyncImageViewController

@synthesize urlString = _urlString;

#pragma mark - Private

- (void)asyncLoadImage
{
    [spinView setHidden:NO];
    [spinView setHidesWhenStopped:YES];
    [spinView startAnimating];
    
    NSURL *url = [NSURL URLWithString:[self.urlString stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]];
    LOG(@"AsyncImageViewController:%@",_urlString);
    
    NSMutableURLRequest *theRequest = [NSMutableURLRequest requestWithURL:url];
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    
    [NSURLConnection sendAsynchronousRequest:theRequest
                                       queue:queue
                                        completionHandler:^( NSURLResponse *response ,NSData *responseData, NSError *aError) {
                                            
                                            UIImage *image = [UIImage imageWithData:responseData];

                                            [self performSelectorOnMainThread:@selector(didAsyncLoadImage:) withObject:image waitUntilDone:YES];
                                        }];
}

- (void)didAsyncLoadImage:(UIImage*)image
{
    imageView.image = image;    
    [spinView stopAnimating];
}

#pragma mark - View Life

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self asyncLoadImage];
    
    [self setTitle:@"Photo"];
    [self setBackButtonImageActiveName:@""
                          inactiveName:@"back-button"
                                target:self
                                action:@selector(back)];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Action

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

@end
